"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : Compatibility
Case Name   : 向间隔分区表中导入数据
Create At   : 2023/06/02
Owner       : n@ningyali
Description :
        1.创建间隔分区表
        2.导入合规数据
        3.导入不合规数据
Expect      :
        1.成功
        2.成功
        3.成功
History     :
"""
import os
import unittest

from yat.test import Node

from testcase.COMPATIBILITY.GRAMMAR.LOAD. \
    Opengauss_Compatibility_Grammar_Load_Common import LoadData
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Logger import Logger


class LoadData0062(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.common = Common()
        self.load_data = LoadData()
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.pri_user = Node('PrimaryDbUser')
        self.case_lable = 'load_data_0062'
        self.db_name = f'db_{self.case_lable}'
        self.t_name = f't_{self.case_lable}'
        self.file_path = os.path.join('/home', self.pri_user.ssh_user)
        self.cols = 'c_01 number primary key,c_02 date unique'
        self.partitions = "partition p1 values less than ('2022-12-11')," \
                          "partition p2 values less than ('2023-12-12')," \
                          "partition p3 values less than ('2023-12-13')," \
                          "partition p4 values less than ('2023-12-14')"

        text1 = '-----创建数据文件；expect:创建成功-----'
        self.log.info(text1)
        self.data1 = "#1001,'2022-12-11'##1002,'2022-12-12'#" \
                     "#1003,'2022-12-13'##1004,'2022-12-14'#"
        self.data2 = "#1001,'2023-12-14'##1002,'2023-12-15'#"
        res = self.load_data.create_data_file(self.pri_user, self.case_lable,
                                              self.data1, self.data2)
        self.assertTrue(res, '执行失败:' + text1)

        text2 = '-----创建兼容B库；expect:创建成功-----'
        self.log.info(text2)
        res = self.load_data.create_b_db(self.pri_sh, self.db_name)
        self.assertTrue(res, '执行失败:' + text2)

    def test_load(self):
        text = '--------step1：创建间隔分区表；expect：建表成功--------'
        self.log.info(text)
        res = self.load_data.create_partition_table(
            self.pri_sh, self.db_name, self.t_name, self.cols,
            partition_by='range', partition_key='c_02',
            suf_params="interval('1 day')", partitions=self.partitions)
        self.assertTrue(res, '执行失败:' + text)

        text = '------step2：导入合规数据；expect：成功------'
        self.log.info(text)
        f_path = os.path.join(self.file_path, f'{self.case_lable}_1.txt')
        self.load_data.load_data(self.pri_sh, self.db_name,
                                 self.t_name, f_path,
                                 line_start='#', line_end='#',
                                 into_type='')
        sql = f'select * from {self.t_name} partition (p2);'
        res = self.pri_sh.execut_db_sql(sql, dbname=self.db_name)
        rows, _ = self.common.parse_sql_query_res(res)
        expect = [['1001', '2022-12-11'], ['1002', '2022-12-12'],
                  ['1003', '2022-12-13'], ['1004', '2022-12-14']]
        self.assertEqual(rows, expect, '执行失败' + text)

        text = '--------step3：导入不合规数据；expect：成功--------'
        self.log.info(text)
        f_path = os.path.join(self.file_path, f'{self.case_lable}_2.txt')
        self.load_data.load_data(self.pri_sh, self.db_name,
                                 self.t_name, f_path,
                                 line_start='#', line_end='#',
                                 into_type='')
        sql = f"select t1.relname, partstrategy, boundaries " \
            f"from pg_partition t1, pg_class t2 " \
            f"where t1.parentid = t2.oid " \
            f"and t2.relname = '{self.t_name}' " \
            f"and t1.parttype = 'p';"
        res = self.pri_sh.execut_db_sql(sql, dbname=self.db_name)
        rows, _ = self.common.parse_sql_query_res(res)
        expect = [['sys_p2', 'i', '{2023-12-16}'],
                  ['sys_p1', 'i', '{2023-12-15}'],
                  ['p4', 'r', '{2023-12-14}'], ['p3', 'r', '{2023-12-13}'],
                  ['p2', 'r', '{2023-12-12}'], ['p1', 'r', '{2022-12-11}']]
        self.assertEqual(rows, expect, '执行失败' + text)

    def tearDown(self):
        self.log.info('-----清理环境-----')
        res = self.load_data.clear_env(self.pri_sh, self.pri_user,
                                       self.db_name,
                                       os.path.join(self.file_path,
                                                    f"{self.case_lable}*"))
        self.assertTrue(res, '执行失败:清理环境')
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
